﻿#include "QProcessPro.h"
#include <QFileInfo>
#include <QDir>
#include <QTextCodec>
#include <QDebug>

QProcessPro::QProcessPro(QString exePath, QStringList arguments, QObject *parent) : QObject(parent),
    _process(this)
{
    _process.setReadChannelMode(QProcess::MergedChannels);
    QFileInfo fileInfo(exePath);
    if(!fileInfo.exists())
    {
        qDebug()<<QString("QProcessPro 该程序不存在 %1").arg(exePath);
    }
    _process.setWorkingDirectory(fileInfo.dir().absolutePath());
    _process.setProgram(exePath);
    QList<QByteArray> argsEncoded;
    for(QString arg:arguments)
    {
        argsEncoded.append(arg.toUtf8());
    }
    _process.setArguments(arguments);
    // 设置要启动的程序及其参数
    connect(&_process, &QProcess::readyRead, [this]() {
            PrintProcessLog(_process);
    });

    connect(&_process, &QProcess::errorOccurred, [this](QProcess::ProcessError error) {
            qDebug()<<__FUNCTION__<<__LINE__<<error;
    });
    _code="utf-8";
}

void QProcessPro::SetCode(QString code_)
{
    _code=code_;
}

void QProcessPro::Execute()
{
    _process.start();
    _process.waitForFinished();
}

void QProcessPro::ExecuteNoWait()
{
     _process.start();
     _process.waitForStarted();
}

QStringList QProcessPro::GetPrintLog()
{
    QStringList ret;
    for(QString a:_printItems)
    {
        if(a.count()!=0)
        {
            ret.append(a);
        }
    }
    return ret;
}

bool QProcessPro::IsRunning()
{
    return _process.state()==QProcess::Running;
}

void QProcessPro::PrintProcessLog(QProcess &process)
{
    QString str = ReadAll(process);
    _printItems.append(str.split("\r\n"));
}

QString QProcessPro::ReadAll(QProcess &process)
{
    QByteArray qba =process.readAll();
    QTextCodec* pTextCodec = QTextCodec::codecForName(_code.toStdString().c_str());
    QString str = pTextCodec->toUnicode(qba);
    return str;
}

